const router = require('koa-router')()

router.prefix('/dept')

let departments = [];

function getDepartments(parentId) {
    const result = [];
    for (let department of departments) {
        if (department.pCode == parentId) {
            const children = getDepartments(department.code);
            if (children.length > 0) {
                department.children = children;
            }
            result.push(department);
        }
    }
    return result;
}



router.get('/', async (ctx, next) => {
    let userName = ctx.query.user;
    let selectDept = "select * from organization";

    let departList = await ctx.db.EXECUTE(selectDept);

    departments = departList;
    let result = getDepartments(1);
    if(result.length > 0) {
        ctx.body = {
            status: 'ok',
            departments: result
        }
    }
})

router.post('/add', async (ctx, next) => {
    console.log(ctx.request.body);
    let pCode = ctx.request.body.departId;
    let newDepartment = ctx.request.body.newDepartment;
    let code = ctx.request.body.code;

    let insertSql = "insert into organization (organizationName, pCode, code) values(?, ?, ?)";
    let result = await ctx.db.EXECUTE(insertSql, newDepartment, pCode, code);

    if(result.affectedRows > 0) {
        ctx.body = {
            status: 'ok'
        }
    }
})



module.exports = router
